<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use DB;

class ZksController extends Controller
{
	private $iniOrder = [['addr','hb6303'], ['users', 'client'], ['stations'], ['tester', 'contract', 'expire'], ['stationPcShare'], ['vcr']];
	private $orderKey;

	public function __construct()
	{
		$this->orderKey = domain() . 'ZksOrder';
		// cache()->forget($this->orderKey);
	}

	public function setOrder()
	{
		$order = cache($this->orderKey, $this->iniOrder);
		$chag = 0;
		if ($postOrder = request('order', '')) {
			foreach ($order as $k1 => $val1) {
				foreach ($val1 as $k2 => $val2) {
					if ($val2 == $postOrder[0]) {
						$chag += 1;
						$order[$k1][$k2] = $postOrder[1];
					}
					if ($val2 == $postOrder[1]) {
						$chag += 1;
						$order[$k1][$k2] = $postOrder[0];
					}
					if ($chag === 2) {
						break;
					}
				}
			}
			cache([$this->orderKey => $order], 99999);
		}
		return 1;
	}

	public function index()
	{
		$data = $this->getContent();
		$order = cache($this->orderKey, $this->iniOrder);
		//排序
		$data['order'] = $order;

		//获取用户当前的地址
		if (config('constant.is_lan')) {
			$data['addr'] = [];
		}else{
			$data['addr'] = curl("http://api.map.baidu.com/location/ip?ak=dELXcqGX0714b9wv6H8f5wsLRyC0mVUN&ip=" . request()->getClientIp() . "&coor=bd09ll");
		}
		//温湿度大气压计
		$data['hb6303'] = $this->getEnvInfo();
		//录像机
		//$content = DB::table('a_vcr')->where('ishide', 0)->where('lan_ip', '!=', '')->where('server_lan_ip', '!=', '')->select('name', 'lan_ip', 'server_lan_ip', 'channel_count','username','password')->get();

        $zksTitle = DB::table('setting_sys')->where('key','zks_title')->value('value') ?: '安全工器具检测中控平台';
		return view('admin.zks.index', compact('data','zksTitle'));
	}

	//管理员
	public function manager($id)
	{
		$data = DB::table('manager')->find($id);
		$roleIds = explode(',', $data->role_ids ?: $data->role_id);
		$roleNames = DB::table('role')->whereIn('id', $roleIds)->pluck('role_name')->toArray();
		$data->role_names = implode(',', $roleNames);
		return view('admin.zks.manager', compact('data'));
	}

	//客户
	public function client($id)
	{
		$data = DB::table('a_client')->find($id);
		return view('admin.zks.client', compact('data'));
	}

	//批次
	public function contract($id)
	{
		$data = DB::table('a_contract_gaiyao as a')->leftJoin('a_contract as b', 'a.contract_id', '=', 'b.id')->where('b.id', $id)->get();
		return view('admin.zks.contract', compact('data'));
	}

	//到期
	public function expire($clientName)
	{
		$seting = getCache('setting');
		$nexttimelimit = date('Y-m-d', strtotime('+' . unserialize($seting['warn_days_limit'])['days'] . ' days'));
		$nextMintimelimit = date('Y-m-d', strtotime('-15 days'));
		$data = DB::table('a_sample_info as a')
				->leftJoin('a_contract as b', 'a.contract_id', '=', 'b.id')
				->leftJoin('a_contract_gaiyao as c', 'a.contract_gaiyao_id', '=', 'c.id')
				->where('b.client_name', '=', $clientName)
				->whereDate('a.next_time', '>', $nextMintimelimit)
				->whereDate('a.next_time', '<', $nexttimelimit)
				->where('a.res', 1)->where('a.notice', 1)
				->select('a.bar_code', 'a.contract_id', 'a.contract_gaiyao_id', 'a.next_time', 'a.gqj_ID', 'b.client_name', 'c.tool_name')
				->get();   //樣品信息
		return view('admin.zks.expire', compact('data'));
	}

	//设备
	public function station($id)
	{
		$data = DB::table('a_station')->find($id);
		$dbStat = StationController::dbStat();
		foreach ($dbStat as $col => $value) {
			$data->$col = $value[$data->$col];
		}
		return view('admin.zks.station', compact('data'));
	}

	//今日主检工作量转为今日完成量
	public function tester($tool_name)
	{
		$date = date('Y-m-d');
        $data = DB::table('a_sample_info as a')->leftjoin('a_contract_gaiyao as b','a.contract_gaiyao_id','=','b.id')->leftjoin('a_third_data as c','c.bar_code','=','a.bar_code')->where('b.tool_name',$tool_name)->whereDate('a.test_time',$date)->select('b.tool_name','a.bar_code','a.self_num','a.res','c.third_tool_name')->orderBy('a.test_time','desc')->get();
		return view('admin.zks.today', compact('data'));
	}
    //录像机
    public function vcr($lanip)
    {
        $info = DB::table('a_vcr')->where('lan_ip',$lanip)->first();
        return view('admin.zks.vcr', compact('info'));
    }
	//温湿度大气压设备详情
	public function hb6303($id){
		$info = DB::table('a_hb6303 as a')
						->leftJoin('a_env_info as b','a.id','=','b.hb6303_id')
						->where('a.id',$id)
						->select('a.*','b.temp','b.humi','b.pressure')
						->orderBy('b.id','desc')
						->first();

		switch($info->type){
			case 'temp_hum':
				$stations = DB::table('a_station')->where('temp_hum_num',$info->dev_num)->get();
				break;
			case 'press':
				$stations = DB::table('a_station')->where('press_num',$info->dev_num)->get();
				break;
			default:
				$stations = DB::table('a_station')->where('temp_hum_num',$info->dev_num)->orWhere('press_num',$info->dev_num)->get();
		}
		return view('admin.zks.hb6303', compact('stations', 'info'));
	}

	//获取最近n秒内增加的数据
	public function getContent(){
		$data = [];
		//用户
		$data['users'] = ['title' => '管理员', 'toMid' => false, 'key' => 'user', 'url' => 'user', 'content' => DB::table('manager')->where('id', '>', '1')->select('id', 'realname as val1', 'username as val2', 'chizheng as val3')->get()];


		//客户信息
		$data['client'] = ['title' => '客户列表', 'toMid' => true, 'key' => 'client', 'url' => 'client', 'column' => ['NO', '送检单位', '联系人', '联系电话', '创建时间'], 'content' => DB::table('a_client')->select('id', 'name as val1', 'contact as val2', 'telephone as val3', 'created_at as val4')->get(),];

		//在受理批次
		$content = DB::table('a_contract')->where([['is_del', '=', 0], ['status', '<', 8]])->select('id', 'batchNum as val1', 'status as val2', 'client_name as val3', 'creator as val4')->orderBy('id', 'desc')->get();
		$dbStat = ContractController::dbStat();
		foreach ($content as $k => $value) {
			$content[$k]->val2 = $dbStat['status'][$value->val2];
		}
		$data['contract'] = ['title' => '在受理批次', 'toMid' => true, 'key' => 'contract', 'url' => 'contract', 'column' => ['NO', '批次号', '状态', '送检单位', '受理人'], 'content' => $content];

		//到期预警
		$seting = getCache('setting');
		$nexttimelimit = date('Y-m-d', strtotime('+' . unserialize($seting['warn_days_limit'])['days'] . ' days'));
		$nextMintimelimit = date('Y-m-d', strtotime('-15 days'));
		$content = DB::table('a_sample_info as a')
				->leftJoin('a_contract as b', 'a.contract_id', '=', 'b.id')
				->whereDate('a.next_time', '<', $nexttimelimit)
				->whereDate('a.next_time', '>', $nextMintimelimit)
				->where('a.notice', 1)
				->where('a.res', 1)
				->select(DB::raw('b.client_name AS id,b.client_name AS val1,COUNT(1) AS val2'))
				->groupBy('b.client_name')->get();
		$client = DB::table('a_client')->select('name', 'contact', 'telephone')->get()->keyBy('name');
		foreach ($content as $k => $item) {
			$content[$k]->val3 = isset($client[$item->val1]) ? $client[$item->val1]->contact : '';
			$content[$k]->val4 = isset($client[$item->val1]) ? $client[$item->val1]->telephone : '';
		}
		$data['expire'] = ['title' => '到期预警', 'toMid' => true, 'key' => 'expire', 'url' => 'expire', 'column' => ['NO', '送检单位', '数量', '联系人', '联系电话'], 'content' => $content];
		// dd($data['expire']);
		//检测设备（工位）
		$stations = DB::table('a_station')->where('status', '<', 4)->orderBy('dev_num', 'asc')->get();
		$dbStat = StationController::dbStat();
		$content = [];
		foreach ($stations as $item) {
			$valAry = ['id' => $item->id, 'val1' => $item->name, 'val2' => $dbStat['status'][$item->status], 'val3' => $item->dev_num, 'val4' => $item->user,];
			array_push($content, (object)$valAry);
		}
		$data['stations'] = ['title' => '检测设备', 'toMid' => true, 'key' => 'stations', 'url' => 'station', 'column' => ['NO', '设备名称', '状态', '设备编号', '负责人'], 'content' => $content];

		//工位屏幕共享监控转为年完成量
        $sql = "SELECT YEAR(test_time) AS val1, COUNT(*) as val2,count(res = 1 OR NULL) as val3 FROM a_sample_info where res!=0 GROUP BY YEAR(test_time)";
        $content = DB::select($sql);
		$data['stationPcShare'] = ['title' => '年完成量', 'toMid' => true, 'key' => 'stationPcShare','url' => 'stationPcShare','column' => ['年份', '完成量', '合格数量'],'content' => $content];

        //录像机转为每月完成量
        $sql = "SELECT MONTH(test_time) AS id,MONTH(test_time) AS val1, COUNT(*) as val2,count(res = 1 OR NULL) as val3,count(res = 2 OR NULL) as val4 FROM a_sample_info where YEAR(test_time) = YEAR(curdate()) and res!=0 GROUP BY MONTH(test_time)";
        $content = DB::select($sql);
        $data['vcr'] = ['title' => '月完成量', 'toMid' => true, 'key' => 'vcr','url'=>'month','column' => ['NO', '月份', '试验数量','合格数量','不合格数量'],  'content' => $content];

		//主捡人转为今日完成量
		$yesterday = date('Y-m-d',time()).' 00:00:00';
		$current_time = date('Y-m-d',time()).' 23:59:59';
        $content = DB::table('a_sample_info AS A')->leftJoin('a_contract_gaiyao AS B', 'A.contract_gaiyao_id', '=', 'B.id')->whereBetween('A.test_time', [$yesterday, $current_time])->select('B.tool_name as id','B.tool_name as val1', DB::raw('Count( res > 0 OR NULL ) AS val2,Count( res = 2 OR NULL ) AS val3, CURDATE() AS val4'))->groupBy('B.tool_name')->orderByRaw('tool_name desc')->get();
		$data['tester'] = ['title' => '今日完成量', 'toMid' => true, 'url' => 'tester', 'key' => 'tester', 'column' => ['NO','工器具名称', '试验数量', '不合格数量', '日期'], 'content' => $content];
		return $data;
	}

	//获取每个月的详细信息
	public function getMonthContent($month){
	    $year = date('Y');
        $data = DB::table('a_sample_info as a')->leftjoin('a_contract_gaiyao as b','a.contract_gaiyao_id','=','b.id')->leftjoin('a_third_data as c','c.bar_code','=','a.bar_code')->whereYear('a.test_time',$year)->whereMonth('a.test_time',$month)->select('c.third_tool_name','b.tool_name','a.bar_code','a.self_num','a.res','a.test_time','a.submit_time')->get();
        return view('admin.zks.month', compact('data'));
    }

	// 温湿度大气压计
	public function getEnvInfo(){
		$sql = "SELECT
                    a.*,c.*
                FROM
                    `a_hb6303` AS `a`
                LEFT JOIN (
                    SELECT
                        max(id) as env_id,
                        dev_num
                    FROM
                        a_env_info
                    GROUP BY
                        dev_num
                ) AS `b` ON `a`.`dev_num` = `b`.`dev_num`
                LEFT JOIN (
                    SELECT
                        id as c_id,temp,humi,pressure,time as last_time
                    FROM
                        a_env_info
                ) AS `c` ON `c`.`c_id` = `b`.`env_id` ";
        $hb6303 = DB::select($sql);
		return $hb6303;
	}
}
